<template>
  <section class="cart-panel-container">
    <section class="table-title">
      <section class="select">
        <n-checkbox
          label="全选"
          class="check-checkbox"
          :checked="!!allCheck"
          @update:checked="toggleAllCheck"
        ></n-checkbox>
      </section>
      <section class="img"></section>
      <section class="product-name">商品名称</section>
      <section class="single-price">单价</section>
      <section class="amount">数量</section>
      <section class="unit-calc">小计</section>
      <section class="options">操作</section>
    </section>
    <n-divider></n-divider>
    <section class="table-body">
      <template v-if="cartInfos.info?.length">
        <section class="table-row" v-for="row in cartInfos.info">
          <section class="select">
            <n-checkbox
              class="check-checkbox"
              @update:checked="() => toggleCheckRow(row)"
              :checked="!!row.selected"
            ></n-checkbox>
          </section>
          <section class="img">
            <n-image
              width="80"
              style="border-radius: 3px;border: 1px solid #3f3f3f11;margin: 0 auto;"
              :src="row.img"
            ></n-image>
          </section>
          <section class="product-name">{{ row.goods_title }} | {{ row.sku_title }}</section>
          <section class="single-price">{{ row.goods_price }} 元</section>
          <section class="amount">
            <n-input-number
              :min="1"
              style="width: 120px;margin: 0 auto;"
              show-button
              @update:value="() => updateCartItem(row)"
              v-model:value="row.goods_num"
            />
          </section>
          <section class="unit-calc">{{ row.goods_price * row.goods_num }} 元</section>
          <section class="options">
            <n-popconfirm
              positive-text="确认"
              negative-text="取消"
              @positive-click="() => deleteCartItem(row)"
            >
              <template #trigger>
                <n-icon size="28" class="delete-cart">
                  <CancelOutlined></CancelOutlined>
                </n-icon>
              </template>
              确认将
              <b>{{ row.goods_title }}</b> 移除购物车吗？
            </n-popconfirm>
          </section>
        </section>
      </template>
      <n-empty v-else class="empty" description="购物车里啥也没有">
        <template #extra>
          <!-- <n-button size="small">看看别的</n-button> -->
        </template>
      </n-empty>
    </section>
  </section>
  <section class="total-calc">
    <section class="amount">
      <router-link to="/mall">继续购物</router-link>
      <span>|</span>
      <span class="amount-info">
        共
        <span>{{ cartInfos.info.length }}</span> 件，已选择
        <span>{{ selectedCount }}</span> 件
      </span>
    </section>
    <section class="price">
      <section class="total">
        合计：
        <span>{{ totalPrice }}</span> 元
      </section>
      <n-button type="primary" @click="pay" :disabled="!payable" class="pay-button">去结算</n-button>
    </section>
  </section>
</template>
<script setup lang="ts">
import { reactive, computed } from '@vue/reactivity';
import { deleteCartService, getCartService, updateCartService } from '../../api/cartApi';
import { createOrderService } from '../../api/orderApi';
import { CancelOutlined } from '@vicons/material';
import { useGlobalMessage, $pushRoute } from '../../utils/global';
import $store from '../../store';

const cartInfos = reactive({
  info: [] as any,
});

getCartService().then(res => {
  cartInfos.info = res.data;
});

const totalPrice = computed(() => cartInfos.info.reduce((last: any, curr: any) => {
  if (!curr.selected) return last;
  return last + curr.goods_num * curr.goods_price;
}, 0));

const payable = computed(() => cartInfos.info.length && cartInfos.info.some((row: any) => row.selected));

const allCheck = computed(() => cartInfos.info.length && cartInfos.info.every((row: any) => row.selected));

const selectedCount = computed(() => {
  let num = 0;
  cartInfos.info.forEach((row: any) => {
    row.selected && (num++);
  })
  return num;
})
function pay() {
  const params: number[] = [];
  cartInfos.info.forEach((row: any) => {
    if (row.selected) params.push(row.id);
  });
  console.log(params);
  createOrderService({
    cartId: params.toString(),
  }).then((res) => {
    console.log(res);
    useGlobalMessage().success('下单成功');
    $store.dispatch('setCartCount', $store.getters.getCartCount - params.length);
    $pushRoute('/order');
  })
}

function updateCartItem(row: any) {
  Promise.resolve().then(() => {
    console.log(row.goods_num);
    updateCartService({
      id: row.id,
      goods_num: row.goods_num,
    });
  })
}

function toggleAllCheck() {
  const value = !allCheck.value;
  cartInfos.info.forEach((row: any) => {
    row.selected = value;
  });
}

function toggleCheckRow(row: any) {
  row.selected = !row.selected;
}

function deleteCartItem(row: any) {
  deleteCartService({
    id: row.id,
  }).then((res) => {
    cartInfos.info.splice(
      cartInfos.info.findIndex((item: any) => row.id === item.id),
      1
    );
    useGlobalMessage().success('删除成功');
    $store.dispatch('setCartCount', cartInfos.info.length);
  })
}
</script>
<style scoped>
.cart-panel-container {
  padding: 20px;
  background-color: #fff;
}
.table-title {
  display: flex;
  font-weight: 600;
  color: #000;
}

.select {
  min-width: 100px;
}
.img {
  width: 80px;
  text-align: center;
  padding-right: 40px;
}

.product-name {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.single-price {
  width: 120px;
  text-align: center;
}

.amount {
  width: 150px;
  text-align: center;
}

.unit-calc {
  width: 120px;
  text-align: center;
  color: #1cb965;
}

.table-title .unit-calc {
  color: #000;
}

.options {
  width: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.empty {
  height: 240px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: row;
}

.check-checkbox {
}

.table-row {
  display: flex;
  height: 100px;
  align-items: center;
}
.table-row + .table-row {
  border-top: 1px solid #3f3f3f11;
}
.total-calc {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  background-color: #fff;
  height: 50px;
  margin-bottom: 40px;
  align-items: center;
  color: #616161;
}

.amount {
  display: flex;
  width: 250px;
  padding-left: 20px;
  justify-content: space-evenly;
}
.amount-info span {
  color: #1cb965;
}

.delete-cart {
  color: #3f3f3f;
  transition: 0.2s ease all;
  cursor: pointer;
}

.delete-cart:hover {
  color: #ee465a;
}

.price {
  display: flex;
  width: 400px;
  align-items: center;
  justify-content: space-between;
  height: 100%;
}

.total {
  color: #1cb965;
  flex: 1;
  text-align: right;
  padding-right: 40px;
  white-space: nowrap;
}

.total span {
  font-size: 24px;
}

.pay-button {
  height: 100%;
  width: 150px;
  border-radius: 0;
}
</style>